--- 模块功能：ADC功能测试.
-- ADC测量精度(10bit，电压测量范围为0到1.85V，分辨率为1850/1024=1.8MV，测量精度误差为20MV)
-- 每隔1s读取一次ADC值
-- @author openLuat
-- @module adc.testAdc
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.14

module(..., package.seeall)
local ready = false
local temp;
function isReady()
    return ready
end

function getTemp()
    return temp
end
local function decodeTemp(r)
    local t
    local a = { 329500, 310900, 293500, 277200, 262000, 247700, 234300, 221700, 209900, 198900, 188500, 178500, 169000, 160200, 151900, 144100, 136700, 129800, 123300, 117100, 111300, 105700, 100500, 95520, 90840, 86430, 82260, 78330, 74610, 71100, 67770, 64569, 61540, 58680, 55970, 53410, 50980, 48680, 44430, 42470, 40570, 38770, 37060, 35440, 33900, 32439, 31050, 29730, 28480, 27280, 27280, 26130, 25030, 23990, 23000, 22050, 21150, 20300, 19480, 18700, 17960, 17240, 16560, 15900, 15280, 14690, 14120, 13580, 13060, 12560, 12090, 11630, 11200, 10780, 10380, 10000, 9632, 9281, 8944, 8622, 8313, 8013, 7728, 7454, 6940, 6699, 6467, 6245, 6032, 5827, 5629, 5438, 5255, 5080, 4911, 4749, 4593, 4443, 4299, 4160, 4160, 4026, 3896, 3771, 3651, 3536, 3425, 3318, 3215, 3116, 3020, 2927, 2838, 2751, 2668, 2588, 2511, 2436, 2364, 2295, 2228, 2163, 2100, 2039, 1980, 1924, 1869, 1816, 1765, 1716, 1622, 1577, 1533, 1492, 1451, 1412, 1373, 1336, 1301, 1266, 1232, 1200, 1168, 1137, 1108, 1079, 1051, 1024, 998, 973 }
    for i, val in ipairs(a) do
        if r > val then
            local t0 = (i - 51) * 1000
            log.info("t0: ", t0)
            local k = (r - val) * 10000 / (val - (a[i - 1]))
            log.info("k: ", k)
            t = t0 + k
            log.info("t: ", t)
            return t / 100
        end
    end
end

local ADC_ID = 0

--- ADC读取测试
-- @return 无
-- @usage read()
local function read()
    -- 打开adc
    adc.open(ADC_ID)
    -- 读取adc
    -- adcval为number类型，表示adc的原始值，无效值为0xFFFF
    -- voltval为number类型，表示转换后的电压值，单位为毫伏，无效值为0xFFFF；adc.read接口返回的voltval放大了3倍，所以需要除以3还原成原始电压
    local adcval, voltval = adc.read(ADC_ID)
    log.info("tval", voltval)
    --log.info("testAdc.read",adcval,(voltval-(voltval%3))/3,voltval)
    --如果adcval有效
    if adcval and adcval ~= 0xFFFF then
    end
    --如果voltval有效
    if voltval and voltval ~= 0xFFFF then
        local vol = voltval * 842 / 1000
        local r = vol * 30000 / (5000 - vol)
        log.info("vol:", vol)
        log.info("r:", r)
        if r ~= nil then
            temp = decodeTemp(r)
            ready = true
        else
            log.error("temper is nill")
        end

    end
    if tonumber((rtos.get_version()):match("Luat_V(%d+)_")) >= 27 then
        adc.close(ADC_ID)
    end
end

sys.timerLoopStart(read, 1000)
